<?php
declare (strict_types=1);

namespace app\wxApi\controller;

use think\Exception;
use think\facade\Db;
use think\Request;
use app\validate\weChat\Examinee as ExamineeValidate;

class Examinee
{
    const TABLE_NAME = 'examinee_baseinfo';

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        try {
            $params = $request->post();
            $cache = $request->cache;
            $validate = new ExamineeValidate();
            if (!$validate->check($params)) {
                throw new Exception($validate->getError(), 9004);
            }
            $details = Db::name('examinee_baseinfo')->find($cache['id']);
            if(empty($details['img'])){
                throw new Exception('头像为空',9005);
            }
            $active = Db::name('active')->find($params['active']);

            // 查询考试信息
            $condition =[
                'active_id'=>$params['active'],
                'examinee_id'=>$cache['id'],
                'level'=>$params['level']
            ];
            $answers = Db::name('answer')->where($condition)->find();
            // 如果当前级别的考试已经处于交卷后的状态（包括已交卷和已阅卷）
            if(!empty($answers)&&$answers['status']!=1){
                throw new Exception('已交卷',2001);
            }
            unset($condition['level']);
            // 查询是否存在过本厂已经提交过的信息
            $oldAnswers = Db::name('answer')->where($condition)->find();
            if(!empty($oldAnswers) && abs((int)$oldAnswers['level']-(int)$params['level'])>1){
                throw new Exception('不允许跨级报名',9003);
            }
            // 查询地区信息
            $area = Db::name('area')->where('name', 'in', $params['area'])->order(['id', 'level'])->select()->toArray();
            if ($area[0]['level'] != 1) {
                $province = Db::name('area')->where('code', '=', $area[0]['parent_id'])->find();
                $city = $area[0];
            } else {
                $province = $area[0];
            }
            $city = isset($area[1])?$area[1]:[];
            foreach ($area as $item) {
                if ($item['parent_id'] == $province['code']) {
                    $city = $item;
                    break;
                }
            }

            $district = isset($area[2])?$area[2]:[];
            foreach ($area as $item) {
                if ($item['parent_id'] == $city['code']) {
                    $district = $item;
                    break;
                }
            }
            $updateData = [
                'id' => $cache['id'],
                'contact_person' => $params['contact_person'],
                'country' => $params['country'],
                'gender' => $params['gender'],
                'id_card' => $params['id_card'],
                'id_type' => $params['id_type'],
                'name' => $params['name'],
                'nation' => $params['nation'],
                'phone' => $params['phone'],
                'country' => $params['country'],
                'province' => $province['name'],
                'province_code' => $province['code'],
                'city' => $city['name'],
                'city_code' => $city['code'],
                'district' => $district['name'],
                'district_code' => $district['code'],
            ];
            $updateResult = Db::name(self::TABLE_NAME)->update($updateData);
            // 创建考试答题表记录
            $answerData = Db::name('answer')->where(['examinee_id' => $updateData['id'], 'active_id' => $params['active'],'level'=>$params['level']])->find();
            $answerData = [
                ...$answerData ?: [],
                'active_id' => $params['active'],
                'examinee_id' => $updateData['id'],
                'level' => $params['level'],
                'type' => $active['type'],
            ];
            $answerResult = Db::name('answer')->save($answerData);
            if ($updateData !== false && $answerResult !== false) {
                return success($updateData);
            } else {
                throw new Exception('修改信息失败', 9005);
            }

        } catch (\Exception $e) {

            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read(int $id, Request $request)
    {
        //
        $cache = $request->cache;

        $condition = [
            'examinee.id' => $cache['id'],
            'active_id' => $id
        ];
        $data = DB::name(self::TABLE_NAME)->alias('examinee')
            ->leftJoin('answer', 'examinee.id=answer.examinee_id')->where($condition)
            ->field(['examinee.*', 'face_url'])->find();
        return success($data);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
    public function answer(Request $request){
        $cache =$request->cache;
        try{
            $params=$request->post();
            if(isset($params['id']) && !empty($params['id'])){
                $update=[
                    'id'=>$params['id'],
                    'examiner_id'=>$cache['id'],
                    'status'=>3,
                    'over_time'=>time()
                ];
                $result= Db::name('answer')->update($update);
                if($result!==false){
                    return success();
                }else{
                    throw new Exception('操作失败',9004);
                }
            }else{
                throw new Exception('非法操作',9005);
            }
        }catch (\Exception $e){
            return error([],$e->getCode()?:9006,$e->getMessage());
        }
    }

}
